package de.easywakeup.appService;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.format.DateUtils;
import de.easywakeup.R;
import de.easywakeup.data.AlarmList;
import de.easywakeup.data.Data;
import de.easywakeup.gui.Alert;

//A broadcast receiver offers us the opportunity to messages that are sent when certain events from the system to intercept and respond to it. We create a new class that extends broadcast receiver.
public class BroadcastReceiverAlarm extends BroadcastReceiver
{

	private Data data;
	private AlarmList al_temp;
	private String extraFlag;

	// Notification ID
	public final static int ID_NOTIFICATION = 0;

	@Override
	public void onReceive( Context context, Intent intent )
	{
		data = Data.singleton( );
		extraFlag = intent.getStringExtra( "AlarmName" );
		al_temp = data.getAlarmListByTime( extraFlag );
		boolean alreadySaidTextToSpeech = intent.getBooleanExtra( "alreadySaidTextToSpeech", false );
		boolean alreadyOpenedAlert = intent.getBooleanExtra( "alreadyOpenedAlert", false );

		String message = "";
		// calls this code, when i send my own designed broadcast
		if( intent.getAction( ).equals( "de.easywakeup.appService.ACTION" ) )
		{
			Intent temp = new Intent( );

			// Check, if Temperature already requested
			if( Integer.parseInt( data.getTemperature( ) ) > 100 )
			{

				if( !alreadyOpenedAlert )
				{
					message = context.getString( R.string.alertmessageTemp1 ) + " " + extraFlag + context.getString( R.string.alertmessageTemp4 );
					temp.putExtra( "message", message );
					temp.setClassName( context, "de.easywakeup.gui.Alert" );
					temp.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
					temp.putExtra( "AlarmName", extraFlag );
					temp.putExtra( "alreadySaidTextToSpeech", alreadySaidTextToSpeech );
					context.startActivity( temp );
					al_temp.setAlreadyOpenedAlert( true );
				}
				generateNotification( context, context.getString( R.string.notificationWithoutWeather ), message );

			}
			else
			{
				if( !alreadyOpenedAlert )
				{
					message = context.getString( R.string.alertmessageTemp1 ) + " " + extraFlag + " " + context.getString( R.string.alertmessageTemp2 ) + " " + data.getTemperature( ) + " " + context.getString( R.string.alertmessageTemp3 );
					temp.putExtra( "message", message );
					temp.setClassName( context, "de.easywakeup.gui.Alert" );
					temp.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
					temp.putExtra( "AlarmName", extraFlag );
					temp.putExtra( "alreadySaidTextToSpeech", alreadySaidTextToSpeech );
					context.startActivity( temp );
					al_temp.setAlreadyOpenedAlert( true );
				}

				generateNotification( context, context.getString( R.string.notificationWithWeather ) + data.getTemperature( ) + " C", message );

			}

		}

		// calls this code, when the smartphone completed the boot process or
		// when the external memory is available
		if( intent.getAction( ).equals( Intent.ACTION_BOOT_COMPLETED ) || intent.getAction( ).equals( Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE ) )
		{
			System.out.println( " Boot completed." );

			// Start Service
			Intent serviceIntent = new Intent( context, AppService.class );
			PendingIntent servicePendingIntent = PendingIntent.getService( context, 0, serviceIntent, 0 );
			long interval = DateUtils.MINUTE_IN_MILLIS * 2; // Interval is all 2
			                                                // Minutes
			long firstStart = System.currentTimeMillis( ) + interval;
			AlarmManager am = (AlarmManager) context.getSystemService( Context.ALARM_SERVICE );
			am.setInexactRepeating( AlarmManager.RTC, firstStart, interval, servicePendingIntent );

			// readData once to stable the application
			PersistenceHandler per = new PersistenceHandler( context, data );
			per.readData( );
		}

	}

	/**
	 * generates a Notification in the action bar
	 * 
	 * @param context
	 *            specific Context, normally this when you call this procedure
	 * @param messageNotification
	 *            Message will be shown in the Action Bar
	 * @param messageActivity
	 *            Message will be shown in the new Activity
	 */
	private void generateNotification( Context context, String messageNotification, String messageActivity )
	{
		int icon = R.drawable.alarm_icon;
		long when = System.currentTimeMillis( );

		// Notifications are issued by sending them to the
		// NotificationManager system service.
		NotificationManager notificationManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE );
		Notification notification = new Notification( icon, messageNotification, when );
		String title = messageNotification;
		String subTitle = messageNotification;
		// Puts the PendingIntent into the notification
		Intent notificationIntent = new Intent( context, Alert.class );
		notificationIntent.putExtra( "AlarmName", extraFlag );
		notificationIntent.putExtra( "message", messageActivity );
		notificationIntent.putExtra( "content", messageNotification );

		PendingIntent intent = PendingIntent.getActivity( context, 0, notificationIntent, 0 );
		notificationIntent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP );

		notification.setLatestEventInfo( context, title, subTitle, intent );

		if( al_temp.getChoosedSound( ) == null )
		{
			// To play the default sound with your notification:
			notification.defaults |= Notification.DEFAULT_SOUND;
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
		}
		// Consider the Checkbox about Vibration before ringing
		if( al_temp.isCheckBoxVibrationClicked( ) )
		{
			notification.defaults |= Notification.DEFAULT_VIBRATE;
		}
		// Builds an anonymous Notification object from the intent, and
		// passes it to the NotificationManager
		notificationManager.notify( ID_NOTIFICATION, notification );

	}

	/**
	 * Stops the Notification
	 * 
	 * @param ctx
	 *            An stable context
	 * @param notifyId
	 *            The specific Notification
	 */
	public static void cancelNotification( Context ctx, int notifyId )
	{
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager nMgr = (NotificationManager) ctx.getSystemService( ns );
		nMgr.cancel( notifyId );
	}

}